package com.user.service.serviceImpl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.ResultCode;
import com.common.Util.ObjectUtil;
import com.user.config.Exception.ServiceExceptionUtil;
import com.user.controller.vo.MenuVo;
import com.user.dao.SysMenuDao;
import com.user.dao.SysRoleDao;
import com.user.dao.SysRoleMenuDao;
import com.user.entity.SysMenu;
import com.user.entity.SysRole;
import com.user.entity.SysRoleMenu;
import com.user.service.IMenu;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: Member_Perks_Store
 * @description:
 * @author: 无恙
 * @create: 2024-06-18 14:23
 **/

@Service
public class IMenuImpl extends ServiceImpl<SysMenuDao, SysMenu> implements IMenu {

    @Resource
    private SysRoleMenuDao roleMenuDao;

    @Resource
    private SysMenuDao menuDao;

    @Resource
    private SysRoleDao roleDao;

    @Override
    public List<MenuVo> listByUid() {

        List<String> roleList = StpUtil.getRoleList();

        //获取角色ID
        List<Long> roleIds = roleDao.selectList(new QueryWrapper<SysRole>().in("role_code", roleList))
                .stream().map(SysRole::getId).collect(Collectors.toList());

        //获取菜单ID
        List<Long> menuIds = roleMenuDao.selectList(new QueryWrapper<SysRoleMenu>().in("role_id", roleIds))
                .stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());

        //获取菜单
        List<SysMenu> menus = menuDao.selectList(new QueryWrapper<SysMenu>().in("id", menuIds));

        return this.buildMenus(menus);


    }

    @Override
    public List<MenuVo> buildMenus(List<SysMenu> menus) {
        if (menus == null || menus.isEmpty()) {
           throw ServiceExceptionUtil.exception(ResultCode.FAILED);
        }
        List<MenuVo> collect = menus.stream().map(m -> {
            MenuVo covert;
            try {
                covert = ObjectUtil.covert(m, MenuVo.class);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            return covert;
        }).collect(Collectors.toList());

        //判断是否为空
        if(collect.isEmpty()) {
            throw ServiceExceptionUtil.exception(ResultCode.FAILED);
        }

        return collect;
    }
}
